export default class Stack<T> {
  private steps: number = 0 //栈总索引
  private steps_run: number = 0 //当前所在栈索引
  private history: T[] = []
  /**
   * @param type 0=出栈，1=进栈
   * @param option 进栈数据
   */
  private setHistory(type: 0 | 1, option?: T) {
    const count = type ? 1 : -1
    this.steps += count
    this.steps_run += count

    type && option ?
      this.history.push(option) :
      this.history.pop()
  }
  // 后退一步
  back(): void {
    if (this.steps_run > 0) this.steps_run--
  }
  // 前进一步
  go(): void {
    if (this.steps_run < this.steps) this.steps_run++
  }
  // 进栈
  push(option: T): void {
    if (!option) throw new Error('请传入数据')
    this.setHistory(1, option)
  }
  // 出栈
  pop(): void {
    this.setHistory(0)
  }
  // 获取当前栈数据
  getCurrent(): T | null {
    if(this.steps_run == 0) return null
    return this.history[this.steps_run - 1]
  }
  // 清除栈数据
  clear(): void {
    this.steps = 0
    this.steps_run = 0
    this.history.length = 0
  }
  getSteps(): number {
    return this.steps
  }
  getCurSteps(): number {
    return this.steps_run
  }
}